package com.fred.util

import com.fred.bean.KeyStoreAlias
import com.fred.bean.KeyStoreBean
import java.io.File
import java.io.FileInputStream
import java.security.KeyStore


object KeyStoreUtil {

    fun getKeyStore(path: String, password: String): KeyStoreBean {
        val keyStoreBean = KeyStoreBean()
        try {
            val keyStore = KeyStore.getInstance("JKS")
            val file = File(path)
            if (!file.exists()) {
                keyStoreBean.code = -1
                keyStoreBean.errorMess = "file not find"
                return keyStoreBean
            }
            val fileInputStream = FileInputStream(file)

            keyStore.load(fileInputStream, password.toCharArray())
            fileInputStream.close()
            keyStore.aliases().toList().forEach {
                keyStoreBean.alias.add(KeyStoreAlias(alias = it))
            }
            keyStoreBean.keyStorePath = path
            keyStoreBean.keyStorePassword = password
            keyStoreBean.code = 0
            keyStoreBean.errorMess = ""
        } catch (e: Exception) {
            keyStoreBean.code = -10
            keyStoreBean.errorMess = e.message ?: ""
        }
        return keyStoreBean
    }

    fun verificationAlias(bean: KeyStoreBean,alias:String,aliasPass:String):KeyStoreBean {
        try {
            val keyStore = KeyStore.getInstance("JKS")
            val file = File(bean.keyStorePath)
            if (!file.exists()) {
                bean.code = -1
                bean.errorMess = "KeyStore File Not Find"
                return bean
            }
            val fileInputStream = FileInputStream(file)
            keyStore.load(fileInputStream, bean.keyStorePassword.toCharArray())
            fileInputStream.close()
            val keyStoreAlias = bean.alias.find { it.alias == alias }
            if (keyStoreAlias == null) {
                bean.code = -2
                bean.errorMess = "Alias Not Find"
                return bean
            }
            val privateKey = keyStore.getKey(keyStoreAlias.alias, aliasPass.toCharArray())
            if (privateKey == null) {
                bean.code = -3
                bean.errorMess = "Alias does not exist or does not identify a key"
                return bean
            }
            keyStoreAlias.password = aliasPass
            bean.code = 0
            bean.errorMess = ""
            return bean
        } catch (e: Exception) {
            bean.code = -10
            bean.errorMess = e.message?:""
            return bean
        }
    }

}